package com.kkwrite.regimen.provider.service.shop;

import com.kkwrite.regimen.common.entity.dto.item.ItemDetailDTO;
import com.kkwrite.regimen.common.entity.dto.shop.ShopDetailDTO;
import com.kkwrite.regimen.common.entity.dto.shopItem.InsertShopItemInDTO;
import com.kkwrite.regimen.common.entity.dto.shopItem.InsertShopItemOutDTO;
import com.kkwrite.regimen.common.entity.dto.shopItem.ShopItemDTO;
import com.kkwrite.regimen.provider.domain.RegItemDO;
import com.kkwrite.regimen.provider.domain.RegPictureDO;
import com.kkwrite.regimen.provider.domain.RegShopDO;
import com.kkwrite.regimen.provider.domain.RegShopItemDO;
import com.kkwrite.regimen.provider.exception.ServiceException;
import com.kkwrite.regimen.provider.repository.RegItemRepository;
import com.kkwrite.regimen.provider.repository.RegPictureRepository;
import com.kkwrite.regimen.provider.repository.RegShopItemRepository;
import com.kkwrite.regimen.provider.repository.RegShopRepository;
import com.kkwrite.regimen.provider.service.item.ItemService;
import com.kkwrite.regimen.provider.util.LocationUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.data.domain.Example;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.sql.Timestamp;
import java.text.DecimalFormat;
import java.util.ArrayList;
import java.util.List;
import java.util.Optional;

/**
 *
 * @author jinying
 */
@Service("shopItemService")
public class ShopItemServiceImpl implements ShopItemService {

	@Resource(name = "regShopItemRepository")
	private RegShopItemRepository regShopItemRepository;

	@Resource(name = "itemService")
	private ItemService itemService;
	
	@Resource(name = "regItemRepository")
	private RegItemRepository regItemRepository;

	@Resource(name = "regShopRepository")
	private RegShopRepository regShopRepository;

	@Resource(name = "shopService")
	private ShopService shopService;
	
	@Resource(name = "regPictureRepository")
	private RegPictureRepository regPictureRepository;

	@Override
	public List<ShopItemDTO> queryShopByItem(Long itemId, String shopKeywords,
			double lat, double lng,String city) throws ServiceException {
		List<RegShopItemDO> shopItemList = regShopItemRepository
				.findAllByItemId(itemId);
		List<ShopItemDTO> shopItemDtoList = new ArrayList<>();
		if (itemId == null) {
			return null;
		}
		if (shopItemList != null) {
			for (RegShopItemDO aShopItemList : shopItemList) {
				ShopItemDTO shopItemDto = new ShopItemDTO();
				Long shopId = aShopItemList.getShopId();
				// 查询店铺
				RegShopDO regShopDo = regShopRepository
						.findByShopIdAndShopKeywordsLike(shopId, shopKeywords,city);
				if (regShopDo == null) {
					continue;
				}
				// 查店铺详情
				ShopDetailDTO shopDetailDto = shopService.getShopDetail(shopId);
				//查询店铺封面图
				RegPictureDO regPictureDoParam = new RegPictureDO();
				regPictureDoParam.setPictureOwnerId(shopId);
				regPictureDoParam.setPictureOwnerType((short) 1);
				regPictureDoParam.setPictureType((short) 11);
				RegPictureDO regPictureDO = regPictureRepository.findOne(Example.of(regPictureDoParam)).orElseThrow(RuntimeException::new);
				// 将查出的Float转为Decimal
				if (shopDetailDto.getLatitude() != null) {
					BigDecimal doubleLat = new BigDecimal(
							String.valueOf(shopDetailDto.getLatitude()));
					double lat1 = doubleLat.doubleValue();
					if (shopDetailDto.getLongitude() != null) {
						BigDecimal doubleLng = new BigDecimal(
								String.valueOf(shopDetailDto.getLongitude()));
						double lng1 = doubleLng.doubleValue();
						if (lat1 != 0.00 && lng1 != 0.00) {
							Double distance = LocationUtils.getDistance(lat1,
									lng1, lat, lng);
							// 根据经纬度求距离
							shopItemDto.setDistance(Integer.parseInt(new DecimalFormat("0").format(distance)));
						}
					}
				}
				ItemDetailDTO itemDetailDTO = itemService.getItemDetail(itemId);
				BeanUtils.copyProperties(regShopDo, shopItemDto);
				BeanUtils.copyProperties(shopDetailDto, shopItemDto);
				BeanUtils.copyProperties(itemDetailDTO, shopItemDto);
				BeanUtils.copyProperties(aShopItemList, shopItemDto);
				shopItemDto.setPictureUrl(regPictureDO.getPictureUrl());

				shopItemDtoList.add(shopItemDto);
			}
		}
		//对店铺根据距离排序
		System.out.println(shopItemDtoList.toString());
		shopItemDtoList.sort((s1, s2) -> {
			if (s1.getDistance() == null) {
				return 1;
			} else if (s2.getDistance() == null) {
				return -1;
			} else if (s1.getDistance() - (s2.getDistance()) != 0) {
				return (s1.getDistance() - (s2.getDistance()));
			} else {
				return s1.getDistance().compareTo(s2.getDistance());
			}
		});
		for (ShopItemDTO aShopItemDtoList : shopItemDtoList) {
			System.out.println("项目店铺详情：" + aShopItemDtoList.toString());
		}
		for (ShopItemDTO aShopItemDtoList : shopItemDtoList) {
			System.out.println("项目距离：" + aShopItemDtoList.getDistance());
		}
		return shopItemDtoList;
	}

	@Override
	@Transactional(rollbackFor = Exception.class)
	public InsertShopItemOutDTO insertShopItem(InsertShopItemInDTO insertShopItemInDTO) {
		Long shopId = insertShopItemInDTO.getShopId();
		Long[] items = insertShopItemInDTO.getItems();
		if(items.length>0){
			for (Long item : items) {
				RegShopItemDO regShopItemDO = new RegShopItemDO();
				Optional<RegItemDO> result = regItemRepository.findById(item);
				if (result.isPresent()) {
					try {
						com.kkwrite.regimen.provider.util.BeanUtils.copyPropertiesSkipNull(result.get(), regShopItemDO);
					} catch (IllegalAccessException e) {
						e.printStackTrace();
					}
					regShopItemDO.setDeleted((short) 0);
					regShopItemDO.setGmtCreate(new Timestamp(System.currentTimeMillis()));
					regShopItemDO.setGmtModified(new Timestamp(System.currentTimeMillis()));
					regShopItemDO.setShopId(shopId);
					regShopItemRepository.saveAndFlush(regShopItemDO);
				}
			}
		}
		return new InsertShopItemOutDTO("success","OK");
	}

}
